package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.GeConExplainFeedbackService;
import com.htgd.gardenexpo.service.GeConExplainService;
import com.htgd.gardenexpo.service.GeConExplainUploadService;
import com.htgd.gardenexpo.service.GeConGisresourceService;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import com.htgd.gardenexpo.utils.UniteUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 17:22
 * @description：电子讲解资源管理
 * @menu: 电子讲解资源管理
 * @modified By：`
 * @version: 1.0
 */

@Api(tags = "电子讲解资源管理")
@RestController
@RequestMapping("/api/explainingresources")
public class ExplainingResourcesController {

    @Value("${upload.url}")
    public String upload_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    @Resource
    private GeConExplainService geConExplainService;
    @Resource
    private GeConExplainUploadService geConExplainUploadService;
    @Resource
    private GeConExplainFeedbackService geConExplainFeedbackService;

    @Resource
    private GeConGisresourceService geConGisresourceService;

    /**
     * 新增电子讲解资源
     */
    @PostMapping(value = "/add")
    public CommonResult<JSONObject> add(@RequestBody GeConExplain geConExplain){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            List<GeConExplain> list=geConExplainService.getExplainByTittle(geConExplain.getExplainTitle());
            if (list!=null&&list.size()>0){
                result.setCode(300);
                result.setMessage("名称不能重复，请重新填写!");
                return  result;
            }
            String uploadIds=geConExplain.getUploadIds();
            geConExplainService.insert(geConExplain);
            if (!uploadIds.equals("")){
                for (String uploadId:uploadIds.split(",")){
                    GeConExplainUpload geConExplainUpload =geConExplainUploadService.queryById(Integer.parseInt(uploadId));
                    geConExplainUpload.setExplainId(geConExplain.getExplainId());
                    geConExplainUploadService.update(geConExplainUpload);
                }
            }
            result.setCode(200);
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadFile")
    public GeConExplainUpload uploadFile(@RequestParam(value = "file") MultipartFile file){

        GeConExplainUpload geConExplainUpload = new GeConExplainUpload();
        String fileName = file.getOriginalFilename();  // 文件名
        geConExplainUpload.setFilename(fileName);
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
                .upload();
        geConExplainUpload.setFilePath(upload_url+fileInfo.getFilename());
        geConExplainUploadService.insert(geConExplainUpload);
        return geConExplainUpload;
    }

    /**
     * 编辑电子讲解资源
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConExplain geConExplain){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            GeConExplain geConExplain1=geConExplainService.queryById(geConExplain.getExplainId());
            if (!geConExplain.getExplainTitle().equals(geConExplain1.getExplainTitle())){
                List<GeConExplain> list=geConExplainService.getExplainByTittle(geConExplain.getExplainTitle());
                if (list!=null&&list.size()>0){
                    result.setCode(300);
                    result.setMessage("名称不能重复，请重新填写!");
                    return  result;
                }
            }
            String uploadIds=geConExplain.getUploadIds();
            geConExplainService.update(geConExplain);
            if (!uploadIds.equals("")&&uploadIds.contains(",")){
                geConExplainUploadService.deleteByIds(uploadIds.split(","),geConExplain.getExplainId());
                for (String uploadId:uploadIds.split(",")){
                    GeConExplainUpload geConExplainUpload =geConExplainUploadService.queryById(Integer.parseInt(uploadId));
                    geConExplainUpload.setExplainId(geConExplain.getExplainId());
                    geConExplainUploadService.update(geConExplainUpload);
                }
            }else {
                geConExplainUploadService.deleteByExplainId(geConExplain.getExplainId());
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除电子讲解资源
     */
    @PostMapping(value = "/delete")
    public CommonResult<JSONObject> delete(int explainId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            List<GeConGisresource> glist=geConGisresourceService.queryByEId(explainId);
            if (glist!=null&&glist.size()>0){
                result.setCode(300);
                result.setMessage("该资源已和景点绑定，无法删除!");
                return result;
            }
            geConExplainService.deleteById(explainId);
            List<GeConExplainUpload> list=geConExplainUploadService.queryByExplainId(explainId);
            for (GeConExplainUpload geConExplainUpload:list){
                String filepath=geConExplainUpload.getFilePath();
                String path=filepath.substring(filepath.indexOf(bucket_name+"/"),filepath.length()-1);
                getAmazonS3Client.delete(path);
            }
            geConExplainUploadService.deleteByExplainId(explainId);
            geConExplainFeedbackService.deleteByExplainId(explainId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 批量删除宣电子讲解
     */
//    @PostMapping(value = "/deleteAll")
    public CommonResult<JSONObject> deleteAll(String explainIds){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            if (explainIds!=null&&!explainIds.equals("")){
                for (String promo:explainIds.split(",")){
                    int promoId= Integer.parseInt(promo);
                    delete(promoId);
                }
            }

            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 历史电子讲解资源检索列表
     */
    @GetMapping(value = "/list")
    public CommonResult<List<GeConExplain>> list(PageQuery pageQuery){
        CommonResult<List<GeConExplain>> result = new CommonResult<>();
        try{
            pageQuery.setPageNum((pageQuery.getPageNum()-1)* pageQuery.getPageSize());
            List<GeConExplain> list=geConExplainService.getAllExplainByValue(pageQuery);
            /*if (list != null && list.size() > 1) {
                for (GeConExplain geConExplain : list) {
                    String content= UniteUtils.stripHtml(geConExplain.getExplainContent().toString());
                    if (!content.equals("")){
                        geConExplain.setExplainContent(content.substring(0,content.length()>200?200:content.length()-1));
                    }else {
                        geConExplain.setExplainContent("");
                    }
                }
            }*/
            pageQuery.setPageSize(0);
            List<GeConExplain> list1=geConExplainService.getAllExplainByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 电子讲解资源发布
     */
    @GetMapping(value = "/release")
    public CommonResult<JSONObject> release(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 电子讲解资源取消发布
     */
    @GetMapping(value = "/unpublish")
    public CommonResult<JSONObject> unpublish(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 电子讲解资源排序
     */
    @GetMapping(value = "/sort")
    public CommonResult<List<Map<String,Object>>> sort(){
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }

    /**
     * 电子讲解资源置顶
     */
    @GetMapping(value = "/top")
    public CommonResult<JSONObject> top(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }


    /**
     * 电子讲解资源审核
     */
    @GetMapping(value = "/review")
    public CommonResult<JSONObject> review( GeConExplain geConExplain){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            GeConExplain geConExplain1=geConExplainService.queryById(geConExplain.getExplainId());
            geConExplain1.setStatus(geConExplain.getStatus());
            String feedback=geConExplain.getFeedback();
            geConExplain1.setReleasetime(new Date());
            geConExplainService.update(geConExplain1);
            if (!feedback.equals("")){
                GeConExplainFeedback geConExplainFeedback = new GeConExplainFeedback();
                geConExplainFeedback.setExplainId(geConExplain.getExplainId());
                geConExplainFeedback.setContent(feedback);
                geConExplainFeedbackService.insert(geConExplainFeedback);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 电子讲解资源审核失败反馈
     */
    @GetMapping(value = "/feedbackInfo")
    public CommonResult<List<GeConExplainFeedback>> feedbackInfo(int explainId){
        CommonResult<List<GeConExplainFeedback>> result = new CommonResult<>();
        try{
            List<GeConExplainFeedback> list=geConExplainFeedbackService.getinfoByEplainId(explainId);
            result.setData(list);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     *  电子讲解资源详情
     */
    @GetMapping(value = "/details")
    public CommonResult<Map<String,Object>> details(int explainId){
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try{
//            Integer explainId=JSON.parseObject(s).getInteger("explainId");
            Map<String, Object> map = new HashMap<>();
            GeConExplain geConExplain=geConExplainService.queryById(explainId);
            map.put("explain",geConExplain);
            List<GeConExplainUpload> geConExplainUploads=geConExplainUploadService.queryByExplainId(explainId);
            map.put("upload",geConExplainUploads);
            PageQuery pageQuery = new PageQuery();
             pageQuery.setReviewStatus("3");
            pageQuery.setPageSize(0);
            List<GeConExplain> nlist=geConExplainService.getAllExplainByValueNoContent(pageQuery);
            List<GeConExplain> list = new ArrayList<>();
            for (int i=0;i<nlist.size();i++){
                GeConExplain geConExplain1=nlist.get(i);
                if (explainId==geConExplain1.getExplainId()){
                    if (nlist.size() >= 3) {
                        if (i < nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            list.add(Conversion(nlist.get(i + 3)));
                            map.put("more", list);
                        } else if (i == nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 2) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 1) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", "");
                            list.add(Conversion(nlist.get(0)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        }
                    } else {
                        if (i == 0 && nlist.size() > 1) {
                            map.put("up", "");
                            map.put("down", Conversion(nlist.get(i + 1)));
                        } else if (i == 0 && nlist.size() == 1) {
                            map.put("up", "");
                            map.put("down", "");
                        } else {
                            map.put("up", Conversion(nlist.get(i - 1)));
                            map.put("down", "");
                        }
                        map.put("more", "");
                    }
                    break;
                }
            }
            result.setData(map);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public GeConExplain  Conversion(GeConExplain geConExplain){
        GeConExplain geConExplain1=geConExplainService.queryById(geConExplain.getExplainId());
        String content=UniteUtils.stripHtml(geConExplain1.getExplainContent().toString());
        if (!content.equals("")){
            geConExplain1.setExplainContent(content.substring(0,content.length()>200?200:content.length()));
        }else {
            geConExplain1.setExplainContent("");
        }
        return geConExplain1;
    }
}
